import device from '@system.device'
import getInstalledApp from './getInstalledApp'
import getBattery from './getBattery'
import getNetwork from './getNetwork'

const getDeviceId = () => {
  const serviceList = ['getUserId', 'getOAID', 'getDeviceId'].map(service => {
    return new Promise(resolve => {
      try {
        device[service]({
          success: resolve,
          fail(e) {
            console.error(e)
            resolve()
          }
        })
      } catch (e) {
        console.warn(e)
        resolve({})
      }
    })
  })

  return new Promise(resolve => {
    Promise.all(serviceList)
      .then(resolve)
      .catch(e => {
        resolve({})
      })
  })
}
const getDeviceInfo = () => {
  return new Promise(resolve => {
    try {
      device.getInfo({
        success(data) {
          resolve(data)
        },
        fail(e) {
          console.error(e)
          resolve({})
        }
      })
    } catch (e) {
      console.error(e)
      resolve({})
    }
  })
}
export default function($this) {
  const appList = $this.$app.MS_APP_LIST
  if ($this.$app.MS_DEVICE_INFO) {
    return Promise.reject($this.$app.MS_DEVICE_INFO)
  }
  const PermissionList = [
    getDeviceInfo,
    getInstalledApp,
    getBattery,
    getDeviceId,
    getNetwork
  ].map(getService => {
    return new Promise(resolve => {
      getService(appList)
        .then(resolve)
        .catch(e => {
          resolve({ data: undefined })
        })
    })
  })
  return Promise.all(PermissionList)
}
